import React, { Component } from 'react';
import { NavigationEvents } from 'react-navigation';
import {
  StyleSheet, Text, View, TouchableOpacity,
  Image, PixelRatio, FlatList, ScrollView, Alert
} from "react-native";
import { API, API_GENERATE } from '../../../../config/api';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import HTTP from '../../../../utils/http';
import ToastUtil from '../../../../utils/toast';
import { Common } from '../../../../component/common/Common';
import { RefuseModal } from '../../../../component/ModalVerifylComponent.js';
import { CommonDialog } from '../../../../components/common/Dialog';
import { MDMCodeCpt } from "../../highSeas/_components/MDMCodeCpt";
const scale = GLOBAL.SCALE;

export class ProductClaimPage extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    return {
      headerTitle: `产品${navigation.state.params.title}审批`,
      headerTintColor: style.color.white,
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
      headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../../imgs/goBackEmpty.png')} />),
      headerStyle: style.head.headerStyle,
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center',
      }
    }
  };

  constructor(props) {
    super(props);
    const { choice } = props.navigation.state.params || {};
    this.choice = choice;
    this.state = {
      titles: this.props.navigation.state.params.title,
      tabIndex: 0,
      applyId: this.props.navigation.state.params.applyId,
      itemDatas: {},
      status: 'data',
      statusCode: 'data',
      refreshIcon: false,
      confirmBtnText: '',
      isJudge: this.props.navigation.state.params.isJudge,
      modalVisible: false,
      itemData: {}
    }
    this.reload = true; // 判断是整个页面刷新还是下拉刷新

  }

  async componentDidMount () {
    this.initPage();
  }
  async	componentWillMount () {
  }

  //初始化数据
  initPage = async (refreshIcon) => {
    this.setState({
      status: this.reload ? 'loading' : 'data',
      statusCode: this.reload ? 'loading' : 'data',
      refreshIcon: !this.reload
    })
    this.params = {
      applyId: this.state.applyId,
    }
    let res = await HTTP.POST(API_GENERATE(API.PRODUCT_CLAIM_APPLY_DETAIL), this.params)
    if (res) {
      let responseData = res.goodsCategoryList;
      let responseItemData = res.claimCompanyApply;
      this.setState({
        itemDatas: responseItemData,
        listData: responseData,
        statusCode: responseData.length > 0 ? 'data' : 'empty',
        status: responseData && responseData[this.state.tabIndex] ? responseData[this.state.tabIndex].goodsList.length > 0 ? 'data' : 'empty' : 'empty',
        refreshIcon: false,
      })
    } else {
      this.setState({
        status: 'error'
      })
    }
  }

  refresh = () => {
    this.reload = false;
    this.initPage()
  }


  refreshTab = () => {
    this.reload = false;
    this.initPage()
  }

  _tabFn = (tabIndex) => {
    this.setState({
      tabIndex,
    })
  }

  onErrorRefresh = () => {
    this.reload = true;
    this.initPage();
  }

  // 同意
  consentCreate = () => {
    return (
      <View>
        <View style={styles.textRow}>
          <Text style={styles.textRowText}>是否确认本次操作？</Text>
        </View>
      </View>
    )
  }

  onConsentCreate = (type, listData) => {
    let item = this.props.navigation.state.params
    item.auditResult = type;
    item.remark = '';
    if (listData) {
      this.setState({
        showRejectModal: true,
        itemData: item
      })
    } else {
      ToastUtil.showWarning('没有数据')
    }
  }

  // 审批
  approve = async (remark) => {
    const data = this.state.itemData;
    let requestParams = {
      businessKey: data.applyId,
      auditResult: data.auditResult,
      remark,
      corpId: this.choice.corpId,
    };
    let text = requestParams.auditResult != 1 ? '驳回' : '审批';
    this.setState({
      showRejectModal: false,
      status: 'loading'
    })
    let res = await HTTP.POST(API_GENERATE(API.PRODUCT_DEAL_APPLY_AUDIT), requestParams);
    if (res) {
      ToastUtil.showSuccess(`${text}成功`).then(() => {
        this.props.navigation.navigate('GoodsListPage', data)
      })
    } else {
      this.setState({
        status: 'data'
      })
    }
  }

  reloadPage = () => {
    this.reload = true;
    this.initPage();
  }

  _approvalListTab = (data) => {
    let { tabIndex } = this.state;
    let item = data.item;
    let index = data.index;
    return (
      <View>
        <View >
          <View style={{ flexDirection: 'row', position: 'relative', justifyContent: 'center', }}>
            <Text style={[styles.itemProductName, tabIndex == index ? styles.tabItemActive : null]} onPress={() => { this._tabFn(index) }}>{item.goodsCateName}</Text>
          </View>
          {tabIndex == index ? (
            <Text style={{
              width: 12 * scale, height: 12 * scale,
              backgroundColor: '#fff', transform: [{ 'rotate': '45deg' }], position: 'absolute', top: 10 * scale, right: -8 * scale
            }}></Text>
          ) : null
          }
        </View>

      </View>
    )
  }

  _approvalListItim = (data) => {
    let item = data.item;
    let { titles } = this.state;
    if (item && item.claimStaffNames && !Array.isArray(item.claimStaffNames)) {
      item.claimStaffNames = item.claimStaffNames.split(",");
    }
    return (
      <View>
        <View style={styles.ProductListName}>
          <View style={{ position: 'relative', flexDirection: 'row', paddingBottom: 5 * scale }}>
            <Text style={styles.itemProductListName}>{item.goodsName}</Text>
          </View>
          {titles == '认领' ? (
            <View>
              {item.applyStaffNameList && item.applyStaffNameList.map((items, index) => {
                return (
                  <View style={styles.itemaddresstName} key={index}>
                    <Text style={styles.itemName}>{items || '--'}</Text>
                    <Text style={styles.itemNames}>审</Text>
                  </View>
                )
              })
              }
              {item.claimStaffNames && item.claimStaffNames.map((itemData, indexs) => {
                return (
                  <View style={styles.itemaddresstName} key={indexs}>
                    <Text style={styles.itemName}>{itemData || '--'}</Text>
                  </View>
                )
              })}
            </View>
          ) :
            (
              <View>
                {item.staffNameList && item.staffNameList.map((items, index) => {
                  return (
                    <View style={styles.itemaddresstName} key={index}>
                      <Text style={styles.itemName}>{items || '--'}</Text>
                    </View>
                  )
                })
                }
              </View>
            )
          }
        </View>
      </View>
    )
  }

  render () {
    let { tabIndex, itemDatas, listData, refreshIcon, status, statusCode, titles, modalVisible, showRejectModal,
      isJudge, itemData } = this.state;
    let listItemData = listData && listData.length > 0 ? listData[tabIndex].goodsList : listData;
    return (
      <View style={styles.container}>
        <NavigationEvents onWillFocus={() => { this.initPage(); }} />
        <View style={styles.headName}>
          <Text style={[styles.headBoxName]}>{itemDatas.companyName || '--'}</Text>
          {!itemDatas.mdmCode ? <MDMCodeCpt /> : null}
        </View>
        {titles == '认领' ? (
          <View style={styles.headBox}>
            <View style={[styles.tabItems, { flexDirection: 'row', flex: 5, paddingRight: 10 * scale, width: '100%', justifyContent: 'flex-start' }]}>
              <Text style={styles.textNmae}>申请时间： {itemDatas.createTime ? (itemDatas.createTime.length > 11 ? itemDatas.createTime.substr(0, 11) + '' : itemDatas.createTime) : '--'}</Text>
            </View>
            <View style={[{ flexDirection: 'row', width: '100%', flex: 5, justifyContent: 'flex-start', paddingLeft: 40 * scale }]}>
              <Text style={[styles.textNmae, styles.textItemNmae]}>操作人：
              </Text>
              <Text style={[styles.textNmae, { width: 110 * scale }]}>
                {itemDatas.createByName || '--'} | {itemDatas.bizTeamName || '--'}
              </Text>
            </View>
          </View>
        ) : (
            <View>
              <View style={styles.headScope}>
                <Text style={[styles.headScopeName]}>申请时间： {itemDatas.createTime ? (itemDatas.createTime.length > 11 ? itemDatas.createTime.substr(0, 11) + '' : itemDatas.createTime) : '--'}</Text>
              </View>
              <View style={styles.headBox}>
                <View style={[styles.tabItems, { flexDirection: 'row', flex: 5, paddingRight: 10 * scale, width: '100%', justifyContent: 'flex-start' }]}>
                  <Text style={styles.textNmae}>操作人：
                  </Text>
                  <Text style={[styles.textNmae, { width: 120 * scale }]}>
                    {itemDatas.createByName || '--'} |
                    {itemDatas.bizTeamName && itemDatas.bizTeamName ? (
                      itemDatas.bizTeamName.length > 6 ? `${(itemDatas.bizTeamName.substr(0, 6) + '...')}` : `${itemDatas.bizTeamName}`
                    ) : '--'}
                  </Text>
                </View>
                <View style={[{ flexDirection: 'row', width: '100%', flex: 5, justifyContent: 'flex-start', paddingLeft: 40 * scale }]}>
                  <Text style={[styles.textNmae, styles.textItemNmae]}>接收人：
                  </Text>
                  <Text style={[styles.textNmae, { width: 120 * scale }]}>
                    {`${itemDatas.bizStaffName || '--'} `}
                    {itemDatas.bizStaffName && itemDatas.bizStaffOranName ? (
                      itemDatas.bizStaffOranName.length > 3 ? `(${(itemDatas.bizStaffOranName.substr(0, 3) + '...')})` : `(${itemDatas.bizStaffOranName})`
                    ) : '--'}
                  </Text>

                </View>
              </View>
            </View>
          )
        }
        <View style={styles.headScope}>
          <Text style={[styles.headScopeName]}>业务组织： {this.choice.corpName || '--'}</Text>
        </View>
        <View style={styles.headScope}>
          <Text style={[styles.headScopeName]}>本次申请原因； {itemDatas.comments ? itemDatas.comments : '--'}</Text>
        </View>
        {
          statusCode == 'data' ? (
            <View style={styles.product}>
              {/* <View style={styles.productName}>
                <FlatList
                  data={LIST}
                  renderItem={
                    this._approvalListTab
                  }
                  refreshing={refreshIcon}
                  onRefresh={() => { this.refreshTab() }}
                />
              </View> */}
              <ScrollView
                style={styles.productName}
              >
                <View>
                  {listData && listData.map((items, index) => {
                    return (
                      <View key={index} >
                        <View style={{ flexDirection: 'row', position: 'relative', justifyContent: 'center', }}>
                          <Text style={[styles.itemProductName, tabIndex == index ? styles.tabItemActive : null]} onPress={() => { this._tabFn(index) }}>{items.goodsCateName}</Text>
                        </View>
                        {tabIndex == index ? (
                          <Text style={{
                            width: 12 * scale, height: 12 * scale,
                            backgroundColor: '#fff', transform: [{ 'rotate': '45deg' }], position: 'absolute', top: 10 * scale, right: -8 * scale
                          }}></Text>
                        ) : null
                        }
                      </View>
                    )
                  })
                  }
                </View>
              </ScrollView>
              {status == 'data' ? (
                tabIndex == 0 ? (
                  <View style={styles.ProductList}>
                    <FlatList
                      data={listItemData}
                      renderItem={
                        this._approvalListItim
                      }
                      refreshing={refreshIcon}
                      onRefresh={() => { this.refresh() }}
                    />
                  </View>
                ) : (
                    <View style={styles.ProductList}>
                      <FlatList
                        data={listItemData}
                        renderItem={
                          this._approvalListItim
                        }
                        onRefresh={() => { this.refresh() }}
                        refreshing={refreshIcon}
                      />
                    </View>
                  )
              ) : (<View style={styles.ProductList}>
                <PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this.onErrorRefresh} />
              </View>)
              }
            </View>
          ) :
            (<View style={styles.ProductList}>
              <PageStatusIndex status={statusCode} emptyText="暂无记录" onErrorPress={this.onErrorRefresh} />
            </View>)
        }
        <View style={styles.itemArea}>
          <View style={[styles.itemStatus, isJudge == false ? styles.itemStyle : null]}>
            {isJudge == true ? (
              <View style={styles.itemDayTime}>
                <Text style={[styles.consent, styles.consentColor]} onPress={() => { this.onConsentCreate(1, listData) }}>同意</Text>
                <Text style={styles.itemdown}
                  onPress={() => { this.onConsentCreate(1, listData); }}>驳回</Text>
              </View>
            ) : null
            }
          </View>
          <View style={styles.itemNumber}>
            <Text style={styles.itemNumbercenter}>
              {titles == '认领' ? `本次申请${titles}产品数：${itemDatas.goodsCnt}，其中非业务当前经营区域数：${itemDatas.goodsCnt}` : `本次${titles}产品数：${itemDatas.goodsCnt}，其中非业务当前经营区域数：${itemDatas.goodsCnt}`}
            </Text>
          </View>
        </View>

        <RefuseModal
          titleText={'审批意见'}
          placeholderText={itemData.auditResult ? '请输入同意原因' : null}
          propsDefaultValue={itemData.auditResult ? '审批同意' : '审批驳回'}
          visible={showRejectModal}
          btnPress={(text) => {
            this.approve(text);
          }}
          bgPress={() => {
            this.setState({
              showRejectModal: false,
            });
          }} />

        <CommonDialog style={{ paddingBottom: 30 * scale }} modalVisible={modalVisible} title={'提示'} confirmBtnText={'确认'} onConfirmPress={() => {
          this.onConsentCreate()
        }}
          renderCustom={this.consentCreate} onClosePress={() => { this.setState({ modalVisible: false, }) }} />
      </View >
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: style.color.bgGray,
    height: '100%',
    display: 'flex',
    flexDirection: 'column',
  },
  headName: {
    backgroundColor: style.color.themeColor,
    //height: 50 * scale,
    width: '100%',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'flex-start',
    paddingTop: 20 * scale,
    paddingLeft: 23 * scale,
    paddingBottom: 8 * scale
  },
  headBoxName: {
    //width: 250 * scale,
    color: '#FFFFFF',
    fontSize: 14 * scale,
    marginRight: 5 * scale
  },
  headBox: {
    backgroundColor: style.color.themeColor,
    height: 30 * scale,
    width: '100%',
    flexDirection: 'row',
    position: 'relative',
    paddingRight: 20 * scale,
    // justifyContent: 'flex-start'
  },
  tabItems: {
    paddingLeft: 23 * scale,

  },
  textNmae: {
    color: '#FFFFFF',
    fontSize: 11 * scale,

  },
  textItemNmae: {
    // paddingLeft: 40 * scale
    // justifyContent: 'flex-end'
  },
  headScope: {
    backgroundColor: style.color.themeColor,
    height: 30 * scale,
    width: '100%',
    flexDirection: 'row',
    justifyContent: 'flex-start',
    paddingLeft: 23 * scale,
  },
  headScopeName: {
    color: '#FFFFFF',
    fontSize: 11 * scale,
  },
  product: {
    flexDirection: 'row', position: 'relative',
    flex: 1,
  },
  productName: {
    backgroundColor: '#F4F7FE',
    flex: 1,
    // height: 400 * scale,
    // alignItems: 'center',
    paddingTop: 15 * scale,
    // backgroundColor: style.color.bgGray,
    // opacity: .1,
  },
  itemProductName: {
    flexDirection: 'row',
    // fontWeight: '800',
  },
  ProductList: {
    flex: 2,
    flexDirection: 'row', position: 'relative',
    // height: 400 * scale,
    backgroundColor: '#ffffff',
    paddingTop: 15 * scale,
  },
  ProductListName: {
    // flexDirection: 'row',
    // alignItems: 'center',
    // position: 'relative',
    // paddingTop: 15 * scale,
    paddingBottom: 10 * scale

  },
  itemProductName: {
    paddingBottom: 10 * scale,

    paddingTop: 10 * scale,
    fontSize: 14 * scale,
    fontWeight: '300'
  },
  itemaddresstName: {
    position: 'relative',
    flexDirection: 'row',
    paddingLeft: 35 * scale,
  },
  itemProductListName: {
    position: 'relative',
    flexDirection: 'row',
    paddingTop: 8 * scale,
    paddingLeft: 20 * scale,
    fontSize: 14 * scale,

  },
  itemName: {
    position: 'relative',
    flexDirection: 'row',
    color: '#010101',
    paddingTop: 5 * scale,
    fontSize: 10 * scale,
    opacity: 0.7
  },
  itemNames: {
    color: '#F7B500',
    paddingTop: 4 * scale,
    fontSize: 12 * scale,
  },
  marginStyle: {
    marginLeft: 20 * scale,
    // marginRight: 16 * scale
  },
  tabItemActive: {
    fontWeight: '800',
  },
  stateView: {
    flexDirection: 'row',
    marginTop: 15 * scale,
    // marginBottom: 15 * scale,
    flexWrap: 'wrap'
  },
  itemArea: {
    height: 105 * scale,
    backgroundColor: '#ffffff',
    // position: 'relative',
    // bottom: 0 * scale,
    // left: 0,

  },
  itemStatus: {
    flexDirection: 'row',
    // alignItems: 'center',
    position: 'relative',
    backgroundColor: '#ffffff',
    // paddingBottom: 100 * scale,
    borderTopColor: '#D8D8D8',
    borderTopWidth: 1 * scale,
  },
  itemStyle: {
    height: 50 * scale
  },
  itemDayTime: {
    justifyContent: 'flex-end',
    flex: 1,
    flexDirection: 'row',
    paddingTop: 15 * scale,
  },
  consent: {
    paddingRight: 20 * scale,
    paddingLeft: 20 * scale,
    paddingTop: 8 * scale,
    paddingBottom: 8 * scale,
    fontSize: 12 * scale,
    opacity: 1,
    color: '#ffffff',
    alignItems: 'center',
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
    borderRadius: 15 * scale,
    // marginRight: 0 * scale,
    flexDirection: 'row',
    backgroundColor: style.color.themeColor,
    overflow: 'hidden'
  },
  itemdown: {
    fontSize: 12 * scale,
    color: style.color.themeColor,
    alignItems: 'center',
    paddingRight: 20 * scale,
    paddingLeft: 20 * scale,
    paddingTop: 8 * scale,
    paddingBottom: 8 * scale,
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
    borderRadius: 15 * scale,
    marginRight: 20 * scale,
    flexDirection: 'row',
    marginLeft: 10 * scale,
  },
  itemNumber: {
    flexDirection: 'row',
    // alignItems: 'center',
    position: 'relative',
    backgroundColor: '#ffffff',
    paddingBottom: 50 * scale,
    justifyContent: 'center',
  },
  itemNumbercenter: {
    paddingTop: 25 * scale,
    fontSize: 12 * scale
  },
  textRow: {
    position: 'relative',
    flexDirection: 'row',
    justifyContent: 'center',
  },
  textRowText: {
    fontSize: 18 * scale,
    fontWeight: '600',
  },
  textDefine: {
    paddingTop: 10 * scale,
    paddingLeft: 25 * scale,
    paddingRight: 25 * scale,
    paddingBottom: 10 * scale,
    borderRadius: 10 * scale,
    marginTop: 30 * scale,
    overflow: 'hidden',
    backgroundColor: style.color.themeColor,
    position: 'relative',
    flexDirection: 'row',
    justifyContent: 'center',
    fontSize: 14 * scale,
    color: '#ffffff',
  },
})